$(document).ready(function(){
	doDrag();
	doDrop();
	
    changeActiveProject("#sprintBacklogMenu #project_to_user_project_id", "#content", "/sprint_backlog/show");
     
    $(document).on("change", "#sprintBacklogMenu #sprint_backlog_sprint_backlog_id", function(){
     	var projectID = $("#sprintBacklogMenu #project_to_user_project_id").val();
        $( "#content" ).load("/sprint_backlog/show" + "?active_project_id=" + projectID + "&id=" + this.value, function(){
            doDrag();
            doDrop();
        });
    });
    
    showOrHide("#sprintBacklogMenu #showHideProjectChart", "#wrapChart", "Das Projekt Chart ausblenden", "Das Projekt Chart einblenden", "#projectChartIcon", "#sprintbacklog", 108);
    
    showOrHide("#sprintBacklogMenu #showHideSprintInformation", "#wrapSprintInformation", "Sprint Informationen ausblenden", "Sprint Informationen einblenden", "#sprintInformationIcon", "#sprintbacklog", 108);
	
	$( document ).on("click", ".sprintbacklogStory", function(){
		$(".marked").removeClass("marked");
		$(this).addClass("marked");
	});
	
	$( "#sprintbacklog" ).on("click", "a", function(){
		var parts = this.id.split("_");
		
		var action = parts[0];
		var id = parts[1];
		
		if(action == "resetUserStoryRating"){
			$.ajax({
                url: "reset_user_story_rating",
                data: "{\"user_story\":" + id + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                type: "post"
            })
            .done(function() {
        		$("#sprintbacklogStory_"+id).fadeOut(100);
            })
            .fail(function( jqXHR, textStatus) {
                $("#shader").hide();
                showDialog("error", "Fehler beim zur&uuml;cksetzen", "Die ausgewählten User Story konnte nicht aktualisiert werden: " + textStatus);
            });
		}
		
		if(action == "moveUserStory"){
			alert("move");
		}
	});
	
	//Calculate the hight of the div container, which wraps the user stories.
	
	//On resize:
	$( window ).resize(function() {
		$(".sprintbacklogColumn").each(function(){
			$(this).children("div").next().css("top", parseInt($(this).children("div").first().css("height"))+5+"px");
		});
	});
	//On load:
	$(".sprintbacklogColumn").each(function(){
		$(this).children("div").next().css("top", parseInt($(this).children("div").first().css("height"))+5+"px");
	});
	
	$( document ).on("click", ".resetUserStory", function(){
		$(this).parent().parent().load("./reset_user_story_rating?user_story=" + this.id.split("_")[1]);
		$(this).parent().parent().remove();
	});

});

var userStoryStateAtStart = "";
var userStoryId = "";

function doDrag(){
	$(".sprintbacklogStory").draggable({   
	    	scroll: false,
	        appendTo: '#sprintbacklog',
	        snap: true,
	        helper: 'clone',
	        start : function(event, ui) {
	        	userStoryStateAtStart = $(this).parent().attr("id").split("_")[1];
	        	userStoryId = $(this).attr("id").split("_")[1];
	        	ui.helper.css("width", $(this).width());
	        	$(this).css("display", "none");
	        	$(".marked").removeClass("marked");
	        	$(this).addClass("marked");
	        	ui.helper.addClass("marked");
	        },
	        stop: function(event, ui) {
	        	$(this).css("display", "");
	        }		
	});
}

function doDrop(){
	$( ".wrapStories" ).droppable({
			accept: ".sprintbacklogStory",
			drop: function(event, ui){
				var currentState = $(this).attr("id").split("_")[1];
				
				if(currentState != userStoryStateAtStart) {
                                        dropColumn = $(this);
                                        alert(currentState + " - " + userStoryId);
                                        $.post( "update", {
                                            newState: currentState,
                                            id: userStoryId
                                        })
                                        .done(function(data) {
                                            if(data == "false") {
                                                showDialog("error", "Fehler beim speichern!", "Der Status der User Story konnte nicht ge&auml;ndert werden! Bitte Versuchen Sie es später erneut.");
                                            }
                                            else {
                                                $("#sprintbacklogStory_" + userStoryId).remove();
                                                dropColumn.append("<div class=\"sprintbacklogStory marked\" id=\"sprintbacklogStory_"+ userStoryId +"\">" + ui.helper.html() + "</div>");
                                                doDrag();
                                                doDrop();
                                                $.get("show?id="+$("#sprint_backlog_sprint_backlog_id").val(), function(data){
                                                    $("#wrapSprintInformation").html($(data).find("#wrapSprintInformation").html());
                                                    sbDrawChart();
                                                    $(".sprintbacklogHeadline").each(function() {
                                                        id = $(this).attr("id");
                                                        $("#"+id).html($(data).find("#"+id).html());
                                                        //$("#"+id).load("show #" + id);
                                                    });
                                                });
                                            }
                                        })
                                        .fail(function(data) {
                                            showDialog("error", "Fehler beim speichern!", "Der Status der User Story konnte nicht ge&auml;ndert werden! Bitte Versuchen Sie es später erneut.");
                                        });
				}
			}
	});
}